package br.com.seosoft.simplecalcfinan;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import br.com.seosoft.simplecalcfinan.adapters.AdapterPasta;
import br.com.seosoft.simplecalcfinan.bancoDados.BancoDados;
import br.com.seosoft.simplecalcfinan.utils.ChangeLogDialog;
import br.com.seosoft.simplecalcfinan.utils.DatePickerFragment;
import br.com.seosoft.simplecalcfinan.utils.Propaganda;
import br.com.seosoft.simplecalcfinan.utils.TimePickerFragment;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class Ed_Contas extends ActivyGeral {
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */

	public String acao = null;
	public String descricao_conta = null;
	public String saldo = null;
	private Long data = null;
	public String fk_grupo = null;
	public String id_conta = null;
	public Double saldo_unsigined = 0.0;
	private AdView adView;
	public int[] id;
	public String[] descricao;
	public Double[] saldo_conta;
	Spinner spinnerPasta;
	private String position_pasta;
	private MenuItem salvar;
	private Button btnData, btnHora;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setTitle(R.string.conta);
		// TODO Insira seu c��digo aqui
		setContentView(R.layout.editar_conta);

		// obtem os objetos view
		final EditText edtSaldoConta = (EditText) findViewById(R.id.edtSaldoConta);
		btnData = (Button) findViewById(R.id.btnData);
		btnHora = (Button) findViewById(R.id.BtnHora);

		spinnerPasta = (Spinner) findViewById(R.id.spinnerMoverContas);
		ObterParamsTela();
		ListarGrupos();

		Propaganda propaganda = new Propaganda();

		if (!propaganda.verificarClienteJaPago(this)) {
			mostrarBanner();
		}

		VerificaSinal();
		mudaSinal();

		edtSaldoConta.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroupSinal);
				EditText edtSaldoConta = (EditText) findViewById(R.id.edtSaldoConta);

				geral geral = new geral();

				if (!edtSaldoConta.getText().toString().equals("")) {
					rg.setVisibility(View.VISIBLE);
				} else {
					rg.setVisibility(View.INVISIBLE);
				}
			}
		});

	}

	// FUN����O LISTA GRUPOS

	public void ListarGrupos() {

		new ListarGruposThread().execute("");

	}

	public void showDatePickerDialog(View v) {
		DatePickerFragment newFragment = new DatePickerFragment();
		newFragment.show(getSupportFragmentManager(), "datePicker");

	}

	public void showTimePickerDialog(View v) {
		TimePickerFragment newFragment = new TimePickerFragment();
		newFragment.show(getSupportFragmentManager(), "timePicker");

	}

	class ListarGruposThread extends AsyncTask<String, Void, Void> {

		List<geral> geralList = new ArrayList<geral>();
		double aux = 0;
		double total = 0;
		BancoDados bd;
		ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();

			progressDialog = new ProgressDialog(Ed_Contas.this);

			progressDialog.setMessage(getResources().getString(
					R.string.atualizarLista));
			progressDialog.setCancelable(false);
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.show();

			bd = new BancoDados(getApplicationContext(), true);

		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub

			bd.BuscaTodosRegistrosGrupos();

			id = new int[bd.TotalRegistroGrupos()];
			descricao = new String[bd.TotalRegistroGrupos()];
			saldo_conta = new Double[bd.TotalRegistroGrupos()];

			for (int i = 0; i < bd.TotalRegistroGrupos(); i++) {

				bd.ProximoRegistroGrupos();
				// inicia o vetor com o total de registros

				geral geral = new geral();
				geral.setIdGrupo(bd.c.getInt(0));
				geral.setDescGrupo(bd.c.getString(1));
				geral.setTotalContasGrupo(bd.c.getDouble(2));

				geralList.add(geral);

				id[i] = geral.getIdGrupo();
				descricao[i] = geral.getDescGrupo();
				saldo_conta[i] = geral.getTotalContasGrupo();

				// Adiciona cada valor e soma o total
				aux = Double.valueOf(geral.getTotalContasGrupo());
				total = aux + total;
				Log.e(br.com.seosoft.simplecalcfinan.geral.LogCat, "Aux: "
						+ aux);
				Log.e(br.com.seosoft.simplecalcfinan.geral.LogCat, "Total: "
						+ Double.valueOf(total));
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			// FECHA O BANCO DE DADOS
			bd.fechar();
			AdapterPasta adapter = new AdapterPasta(getApplicationContext(),
					geralList);
			spinnerPasta.setAdapter(adapter);
			spinnerPasta.setSelection(Integer.valueOf(position_pasta), true);
			progressDialog.dismiss();
		}

	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		salvar = (MenuItem) menu.findItem(R.id.menuSalvar);
		salvar.setVisible(true);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		getSupportMenuInflater().inflate(R.menu.menu, menu);

		MenuItem logout = (MenuItem) menu.findItem(R.id.menuSair);

		if (geral.logado == true) {
			logout.setVisible(true);
		}

		return super.onCreateOptionsMenu(menu);
	}

	// exibe banner google
	public void mostrarBanner() {

		if (!preference.getBoolean(geral.REMOVEU_ADS, true)) {

			// RevMobBanner banner = revmob.createBanner(this);
			// ViewGroup view = (ViewGroup)
			// findViewById(R.id.BannerEditarConta);
			// view.addView(banner);
			//
			Log.d(geral.LogCat,
					"TAMANHO BANNER: "
							+ getResources().getString(R.string.TAMANHO_BANNER));

			if (getResources().getString(R.string.TAMANHO_BANNER).equals(
					"BANNER")) {
				// Create the adView
				adView = new AdView(this);
				adView.setAdUnitId(geral.id_AdMob);
				adView.setAdSize(AdSize.BANNER);
				Log.d(geral.LogCat, "***** TELA PEQUENA ");
			} else {
				adView = new AdView(this);
				adView.setAdUnitId(geral.id_AdMob);
				adView.setAdSize(AdSize.BANNER);
				Log.d(geral.LogCat, "***** TELA NORMAL ++ ");
			}

			// Lookup your LinearLayout assuming it���s been given
			// the attribute android:id="@+id/mainLayout"
			LinearLayout layout = (LinearLayout) findViewById(R.id.BannerEditarConta);
			layout.removeAllViewsInLayout();
			// Add the adView to it
			layout.addView(adView);

			// Initiate a generic request to load it with an ad
			AdRequest request = new AdRequest.Builder().build();

			// request.addTestDevice(AdRequest.TEST_EMULATOR);// Emulador
			// request.addTestDevice("emulator-5554");// Testar dispositivo
			// Android
			adView.loadAd(request);

		}

	}

	// MUDA O SINAL DO SALDO
	public void VerificaSinal() {

		RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroupSinal);
		EditText edtSaldoConta = (EditText) findViewById(R.id.edtSaldoConta);

		geral geral = new geral();

		if (saldo != null) {

			rg.setVisibility(View.VISIBLE);
			Double sinal = Double.valueOf(saldo);

			if (sinal >= 0) {
				rg.check(R.id.rbReceita);
				edtSaldoConta.setTextColor(geral.mudarCor(sinal));
			}
			if (sinal < 0) {
				rg.check(R.id.rbDespesa);
				edtSaldoConta.setTextColor(geral.mudarCor(sinal));
			}
		}

	}

	// MUDA SINAL EM TEMPO DE EXECU����O
	public void mudaSinal() {

		final RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroupSinal);
		final EditText edtSaldoConta = (EditText) findViewById(R.id.edtSaldoConta);
		// VERIFICA MUDAN��A NO CHECK E FAZ A����ES

		rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				geral geral = new geral();

				if (!edtSaldoConta.getText().toString().equals("")) {

					switch (rg.getCheckedRadioButtonId()) {

					case R.id.rbReceita:
						saldo_unsigined = Double.valueOf(edtSaldoConta
								.getText().toString());
						saldo_unsigined = Math.abs(Double
								.valueOf(saldo_unsigined));
						edtSaldoConta.setText(String.valueOf(saldo_unsigined));
						edtSaldoConta.setTextColor(geral
								.mudarCor(saldo_unsigined));
						Log.e(geral.LogCat, "VERDE::" + saldo_unsigined);
						break;

					case R.id.rbDespesa:
						saldo_unsigined = Double.valueOf(edtSaldoConta
								.getText().toString());
						saldo_unsigined = -saldo_unsigined;
						edtSaldoConta.setText(String.valueOf(saldo_unsigined));
						edtSaldoConta.setTextColor(geral
								.mudarCor(saldo_unsigined));
						Log.e(geral.LogCat, "VERMELHO::" + saldo_unsigined);
						break;
					default:
						break;

					}
				}
			}
		});

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case android.R.id.home:

			Intent parentActivityIntent = new Intent(this, contas.class);
			parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(parentActivityIntent);
			finish();
			return true;

		case R.id.menuRate:

			Uri uri = Uri.parse("market://details?id="
					+ getApplicationContext().getPackageName());
			Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(goToMarket);
			return true;
		case R.id.meuNovidades:

			novidades();
			return true;
		case R.id.menuConfig:

			startActivityForResult(new Intent(getApplicationContext(),
					Config.class), 1);

			return true;

		case R.id.menuSair:

			geral.logado = false;

			android.os.Process.killProcess(android.os.Process.myPid());
			return true;

		case R.id.menuSalvar:
			salvar();
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	// MENU NOVIDADES ALERT DIALOG

	public void novidades() {

		// AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// // Get the layout inflater
		// LayoutInflater inflater = getLayoutInflater();
		//
		// builder.setCancelable(false);
		// builder.setTitle(R.string.novidades);
		//
		// // Inflate and set the layout for the dialog
		// // Pass null as the parent view because its going in the dialog
		// layout
		// builder.setView(inflater.inflate(R.layout.novidades, null))
		// // Add action buttons
		// .setNeutralButton(android.R.string.ok,
		// new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int id) {
		// // sign in the user ...
		// dialog.dismiss();
		// }
		// });
		//
		// AlertDialog dialog = builder.create();
		// dialog.show();

		ChangeLogDialog changeLog = new ChangeLogDialog(this);
		changeLog.show();
	}

	// OBTEM A INTENT DAS ACTIVY
	public void ObterParamsTela() {

		EditText edtDescricaoConta = (EditText) findViewById(R.id.etDescricaoConta);
		EditText edtSaldoConta = (EditText) findViewById(R.id.edtSaldoConta);

		// Obetem parametros da tela principal
		geral geral = new geral();

		Intent it = getIntent();
		if (it != null) {
			acao = it.getStringExtra("acao");
			descricao_conta = it.getStringExtra("descricao_conta");
			saldo = it.getStringExtra("saldo");
			id_conta = it.getStringExtra("id_conta");
			data = it.getLongExtra("data", 0);

			position_pasta = it.getStringExtra("position_pasta");
			fk_grupo = it.getStringExtra("fk_grupo");
			if (acao != null) {
				Log.i(geral.LogCat, "acao: " + acao);

				if (acao.equals("novo")) {
					spinnerPasta.setEnabled(false);

				}
			}
			if (fk_grupo != null) {
				Log.e(geral.LogCat, "INTENT ID_CONTA: " + id_conta);
				Log.e(geral.LogCat, "INTENT POSITION_PASTA: " + position_pasta);
				Log.e(geral.LogCat, "INTENT Fk_GRUPO: " + fk_grupo);
				Log.e(geral.LogCat, "INTENT Desc_CONTA: " + descricao_conta);
				Log.e(geral.LogCat, "INTENT Saldo: " + saldo);
				Log.e(geral.LogCat, "INTENT Data: " + data);
				edtDescricaoConta.setText(descricao_conta);
				edtSaldoConta.setText(saldo);

				SimpleDateFormat formatarDataTotal = new SimpleDateFormat(
						"dd/MM/yyyy H:m", Locale.getDefault());

				Calendar calendar = Calendar.getInstance();

				Date date = new Date(data);

				SimpleDateFormat formatarData = new SimpleDateFormat(
						"yyyy-MM-dd", Locale.getDefault());

				SimpleDateFormat formatarHora = new SimpleDateFormat("H:m:s",
						Locale.getDefault());

				if (data > 0) {
					btnData.setText(formatarData.format(date));
					btnHora.setText(formatarHora.format(date));
				}

			}
		}
	}// fim ObterParamsTela

	// Salvar um novo registro
	public void salvar() {

		SimpleDateFormat formatarDataHora = new SimpleDateFormat("yyyy-MM-dd",
				Locale.getDefault());

		EditText edtDescricaoConta = (EditText) findViewById(R.id.etDescricaoConta);
		EditText edtSaldoConta = (EditText) findViewById(R.id.edtSaldoConta);

		descricao_conta = edtDescricaoConta.getText().toString();
		saldo = edtSaldoConta.getText().toString();

		// Verifica se campos vazios
		if (descricao_conta.equals("") || saldo.equals("")) {

			if (descricao_conta.equals("")) {

				edtDescricaoConta.setError(getResources().getString(
						R.string.campoNaoNulo));
			}
			if (saldo.equals("")) {

				edtSaldoConta.setError(getResources().getString(
						R.string.campoNaoNulo));
			}
			// Toast toast = Toast.makeText(this, "Preencha todos os campos ! ",
			// Toast.LENGTH_SHORT);
			// toast.show();

		} else {
			BancoDados bd = new BancoDados(this, false);

			String dataTotal = "";
			// Gera novo Registro

			Log.v(geral.LogCat, "VALOR DO TEXTO: " + btnData.getText());
			if (acao.equals("novo")) {

				if (!btnData.getText().equals("Data")) {

					if (btnHora.getText().equals("Hora")) {
						btnHora.setText("");

					}

					dataTotal = btnData.getText().toString() + " " +

					dataTotal.trim();

					Boolean salvo = bd.GravaRegistroContas(fk_grupo,
							descricao_conta, saldo, dataTotal);
					Log.v(geral.LogCat, "DATA TOTAL: " + dataTotal);
				} else {

					dataTotal = formatarDataHora.format(System
							.currentTimeMillis());
					Boolean salvo = bd.GravaRegistroContas(fk_grupo,
							descricao_conta, saldo, dataTotal);

				}
				Log.v(geral.LogCat, "DATA TOTAL: " + dataTotal);

				// limpa campos
				edtDescricaoConta.setText("");
				edtSaldoConta.setText("");
				descricao_conta = null;
				saldo = null;

				// Volta valores pra tela principal

				Intent it = new Intent();
				// Seta a mensagem de retorno
				it.putExtra("atualizar", "sim");
				it.putExtra("fk_grupo", fk_grupo);
				// Seta o status do resultado e a Intent
				setResult(1, it);
				// Fim desta activity
				finish();

				// fecha o banco de dados
				bd.fechar();
			}// fim novo registro
			if (acao.equals("editar")) {

				String fk_grupo;

				fk_grupo = String.valueOf(id[spinnerPasta
						.getSelectedItemPosition()]);

				if (!btnData.getText().equals("Data")) {

					if (btnHora.getText().equals("Hora")) {
						btnHora.setText("");

					}

					dataTotal = btnData.getText().toString();

					dataTotal.trim();

					Boolean salvo = bd.EditarRegistroContas(id_conta, fk_grupo,
							descricao_conta, saldo, dataTotal);
				} else {

					dataTotal = formatarDataHora.format(System
							.currentTimeMillis());

					Boolean salvo = bd.EditarRegistroContas(id_conta, fk_grupo,
							descricao_conta, saldo, dataTotal);
				}
				Log.v(geral.LogCat, "DATA TOTAL: " + dataTotal);

				// Volta valores pra tela principal

				// limpa campos
				edtDescricaoConta.setText("");
				edtSaldoConta.setText("");
				descricao_conta = null;
				saldo = null;
				Intent it = new Intent();

				// Seta a mensagem de retorno
				it.putExtra("atualizar", "sim");

				// Seta o status do resultado e a Intent
				setResult(1, it);

				// Fim desta activity
				finish();

				// fecha o banco de dados
				bd.fechar();
			}
		}

	}

	// AO DESTRUIR
	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (adView != null) {
			adView.pause();
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (adView != null) {
			adView.resume();
		}
	}

}
